package com.uobgroup.ews.uam.core.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.uobgroup.ews.uam.core.common.SecurityGroupUtils;
import com.uobgroup.ews.uam.core.dao.ProfileDao;
import com.uobgroup.ews.uam.core.dao.UAMRoleDao;
import com.uobgroup.ews.uam.core.domain.Profile;
import com.uobgroup.ews.uam.core.domain.Reference;
import com.uobgroup.ews.uam.core.domain.UAMRole;
import com.uobgroup.ews.uam.core.exception.CannotDeleteObjectException;

@Service
@Transactional
public class UAMRoleServiceImpl implements UAMRoleService {

   @Autowired
   private UAMRoleDao UAMRoleDao;

   @Autowired
   private ProfileDao profileDao;

   public long countAllUAMRoles() {
      return UAMRoleDao.count();
   }

   public void deleteUAMRole(UAMRole uamRole) {
      List<Profile> profileThatUsesThisRole = profileDao.findProfilesByUAMRole(uamRole);
      if (profileThatUsesThisRole.isEmpty()) {
         UAMRoleDao.delete(uamRole);
      }
      else {
         throw new CannotDeleteObjectException("field_cannot_update");
      }
   }

   public UAMRole findUAMRole(Long id) {
      return UAMRoleDao.findOne(id);
   }

   public List<UAMRole> findAllUAMRoles() {
      return UAMRoleDao.findAll();
   }

   public List<UAMRole> findUAMRoleEntries(int firstResult, int maxResults) {
      return UAMRoleDao.findAll(firstResult, maxResults);
   }

   public void saveUAMRole(UAMRole uamRole) {
      uamRole.setSecurityGroup(SecurityGroupUtils.getSecurityGroup(uamRole));
      UAMRoleDao.save(uamRole);
   }

   public UAMRole updateUAMRole(UAMRole uamRole) {

      return UAMRoleDao.update(uamRole);
   }

   @Override
   public List<UAMRole> findByName(String name) {
      return UAMRoleDao.findByName(name);
   }
   
   public Boolean IsAssignProfile(Long RoleId)
   {
	   return UAMRoleDao.IsAssignProfile(RoleId);
   }
   
   public Boolean IsExistSecurityGroup(UAMRole uamRole)
   {
	   return UAMRoleDao.IsExistSecurityGroup(uamRole);
   }
   /**
    * @author dongn
    */
   @Override
   public long countRoleThatHasRoleTypeReference(Reference roleType) {
      return UAMRoleDao.countRoleThatHasRoleTypeReference(roleType);
   }

   @Override
   public long countRoleThatHasProcessingCentreReference(Reference processingCentre) {
      return UAMRoleDao.countRoleThatHasProcessingCentreReference(processingCentre);
   }

   @Override
   public long countRoleThatHasDepartmentReference(Reference department) {
      return UAMRoleDao.countRoleThatHasDepartmentReference(department);
   }
}
